#include "Encoder.h"
#include <stdio.h>
#include <string.h>
#include <iostream>


#define BITS_NUMBER 32

string  Encoder::decToBin(long number)
{
    if ( number == 0 ) return "0";
    if ( number == 1 ) return "1";

    if ( number % 2 == 0 )
        return decToBin(number / 2) + "0";
    else
        return decToBin(number / 2) + "1";
}

long Encoder::binToDec(string number)
{
	long result = 0, pow = 1;
    for ( long i = number.length() - 1; i >= 0; --i, pow <<= 1 )
        result += (number[i] - '0') * pow;

    return result;
}

long Encoder::eliasGammaEncode(long source, char* dest){
        BitWriter bitwriter(dest);
        string binS = decToBin(source);
        for (long a = 0; a < binS.length() - 1; a++){
			bitwriter.putBit(false);
        }
        for (long a = 0; a <= binS.length() - 1; a++){
        	if (binS[a] == '1')
				bitwriter.putBit(true);
        	else
				bitwriter.putBit(false);
        }

        bitwriter.close();
        char foo[30];
        return bitwriter.toLong();
}

long Encoder::eliasGammaDecode(char* source){
        int numberBits = 0;
        string sourceS = source;
        long dec = binToDec(sourceS);
        return dec;
}


/*long Encoder::eliasDeltaEncode(long source, char* dest){
        long prefix = (long)log2(source);

        this->eliasGammaEncode(prefix + 1, dest);

        BitWriter bitwriter(dest, strlen(dest));
        for (long a = prefix - 1; a >= 0; a--){ // n - 2^log2 en log2
                if (source & 1 << a)
                        bitwriter.putBit(true);
                else
                        bitwriter.putBit(false);
        }

        bitwriter.close();

        return bitwriter.toLong();
}

long Encoder::eliasDeltaDecode(char* source, long code){
        char decode[BITS_NUMBER];
        long prefix = this->eliasGammaDecode(source, decode, code);

        prefix = 1 << (prefix - 1); // 2 ^ (log2(n))

        BitReader bitreader(source, 2 * strlen(decode) + 1);

        return (prefix + bitreader.getValue());
}*/
